﻿using Abp.Domain.Repositories;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using MyCompanyName.AbpZeroTemplate.Authorization.Users.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Authorization;
using Abp;
using MyCompanyName.AbpZeroTemplate.Prm.Project.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;


namespace MyCompanyName.AbpZeroTemplate.Prm.Project
{



    public class ProjectApAppService : AbpZeroTemplateAppServiceBase, IProjectApAppService
    {
        /// <summary>
        /// 项目访客角色ID
        /// </summary>
        private readonly int projectTmpRoleId = 2;
        private readonly UserManager userManager;
        private readonly IRepository<ProjectApplication, int> proAppRepository;
        private readonly IRepository<ProjectInfo, int> proRepository;
        private readonly IRepository<ProjectTeam, int> proTeamRepository;
        private readonly PermissionService permissionService;
        private readonly MailManager mailManagerRepository;
        public ProjectApAppService(
                        UserManager _userManager,
                        IRepository<ProjectApplication, int> _proAppRepository,
                        IRepository<ProjectInfo, int> _proRepository,
                        PermissionService _permissionService,
            IRepository<ProjectTeam, int> _proTeamRepository,
            MailManager _mailManagerRepository
            )
        {
            userManager = _userManager;
            proAppRepository = _proAppRepository;
            proRepository = _proRepository;
            permissionService = _permissionService;
            proTeamRepository = _proTeamRepository;
            mailManagerRepository = _mailManagerRepository;
        }

        public List<UserListDto> GetProAppAuditUsers(string projectno)
        {
            List<UserListDto> results = new List<UserListDto>();
            var p = proRepository.GetAll().Where(x => x.ProjectNo.Equals(projectno)).FirstOrDefault();
            if (p == null)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "没有项目:" + projectno);
            }

            //获取有权限的相关人员。
            var hasPermissionUserIds = permissionService.GetPermissionUsers(p.Id, ProjectFunctions.项目授权);
            var users = userManager.Users.AsQueryable().Where(x => hasPermissionUserIds.Any(t => t == x.Id)).ToList();

            return users.Select(x => new UserListDto()
            {
                Id = x.Id,
                Name = x.Name,
                UserName = x.UserName,
                Surname = x.Surname,
                IsActive = x.IsActive
            }).ToList();

        }


        /// <summary>
        /// 项目申请提交
        /// </summary>
        /// <param name="projectNo"></param>
        /// <param name="effectiveTime"></param>
        /// <param name="expirationTime"></param>
        /// <param name="note"></param>
        /// <returns></returns>
        public async Task SubmitApply(CreateProjectApplicationInPut _app)
        {
            if (!AbpSession.UserId.HasValue)
            {
                return;
            }

            var projectinfo = proRepository.GetAll().Where(x => x.ProjectNo.Equals(_app.projectNo)).FirstOrDefault();
            var app = new ProjectApplication()
            {
                AppNote = _app.note,
                ProjectId = projectinfo.Id,
                AppStatus = Project.AppStatus.未审核,
                AppUserId = (long)AbpSession.UserId,
                CheckNote = string.Empty,
                CheckOn = DateTime.Now,
                CheckUserId = 0,
                EffectiveTime = _app.effectiveTime,
                CreateOn = DateTime.Now,
                ExpirationTime = _app.expirationTime,
                ProjectNo = _app.projectNo,
                ProjectName = projectinfo.ProjectName,
                CheckUsers = _app.auditor
            };

            ProjectApplication px = await proAppRepository.InsertAsync(app);





            #region 项目问题提问
            var user = UserManager.Users.Where(x => x.Id == AbpSession.UserId.Value).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectinfo.ProjectName;
            dic["项目编号"] = projectinfo.ProjectNo;
            dic["产品号"] = projectinfo.ProductNo;
            dic["操作时间"] = DateTime.Now.ToString("yyyy-MM-dd");
            dic["操作人"] = user.Name;
            dic["审批人"] = _app.auditor;
            dic["生效时间"] = _app.effectiveTime.ToString("yyyy-MM-dd");
            dic["失效时间"] = _app.expirationTime.ToString("yyyy-MM-dd");
            dic["申请说明"] = _app.note;
            mailManagerRepository.CreateMailRecord(dic, MailCatelog.申请查看项目, projectinfo.Id);
            #endregion

            return;
        }


        /// <summary>
        /// 项目申请记录
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public List<Dto.ProjectApplicationOutPut> GetApplysForMe(string status)
        {

            if (!AbpSession.UserId.HasValue)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "请重新登陆系统");
            }

            var apps = proAppRepository.GetAll().Where(x => x.CreatorUserId == AbpSession.UserId);

            switch (status)
            {
                case "未审核":
                    apps = apps.Where(x => x.AppStatus == AppStatus.未审核);
                    break;
                case "通过":
                    apps = apps.Where(x => x.AppStatus == AppStatus.已通过);
                    break;
                case "驳回":
                    apps = apps.Where(x => x.AppStatus == AppStatus.已驳回);
                    break;
                default:
                    break;
            }
            return apps.ToList().Select(proApp => new Dto.ProjectApplicationOutPut
            {
                AppNote = proApp.AppNote,
                AppStatus = proApp.AppStatus,
                AppStatusTxt = proApp.AppStatus.ToString(),
                CheckUsers = proApp.CheckUsers,
                AppUserId = proApp.AppUserId,
                CheckNote = proApp.CheckNote,
                CheckOn = proApp.CheckOn,
                CheckUserId = proApp.CheckUserId,
                CreateOn = proApp.CreateOn,
                EffectiveTime = proApp.EffectiveTime,
                ExpirationTime = proApp.ExpirationTime,
                ProjectId = proApp.ProjectId,
                ProjectNo = proApp.ProjectNo,
                ProjectName = proApp.ProjectName

            }).ToList();
        }


        /// <summary>
        /// 根据Id得到项目申请
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Dto.ProjectApplicationOutPut GetProApp(int id)
        {
            var proApp = proAppRepository.Get(id);

            return new Dto.ProjectApplicationOutPut
            {
                AppNote = proApp.AppNote,
                AppStatus = proApp.AppStatus,
                AppUserId = proApp.AppUserId,
                AppUser = userManager.Users.Where(x => x.Id == proApp.AppUserId).FirstOrDefault().UserName,
                CheckNote = proApp.CheckNote,
                CheckOn = proApp.CheckOn,
                CheckUserId = proApp.CheckUserId,
                CreateOn = proApp.CreateOn,
                EffectiveTime = proApp.EffectiveTime,
                ExpirationTime = proApp.ExpirationTime,
                ProjectId = proApp.ProjectId,
                ProjectNo = proApp.ProjectNo,
                ProjectName = proApp.ProjectName
            };
        }


        /// <summary>
        /// 申请历史
        /// </summary>
        /// <returns></returns>
        public List<Dto.ProjectApplicationOutPut> GetApplyHistorys(int id)
        {
            var ap = proAppRepository.Get(id);

            var list = proAppRepository.GetAll().Where(x => x.ProjectId == ap.ProjectId
                && x.AppUserId == AbpSession.UserId
                && x.AppStatus != AppStatus.未审核).OrderByDescending(x => x.Id).ToList();
            return list.Select(proApp => new Dto.ProjectApplicationOutPut
            {
                AppNote = proApp.AppNote,
                AppStatus = proApp.AppStatus,
                AppUserId = proApp.AppUserId,
                CheckNote = proApp.CheckNote,
                CheckOn = proApp.CheckOn,
                CheckUserId = proApp.CheckUserId,
                CreateOn = proApp.CreateOn,
                EffectiveTime = proApp.EffectiveTime,
                ExpirationTime = proApp.ExpirationTime,
                ProjectId = proApp.ProjectId,
                ProjectNo = proApp.ProjectNo,
                ProjectName = proApp.ProjectName,
                AppStatusTxt = proApp.AppStatus.ToString(),
                CheckUsers = proApp.CheckUsers
            }).ToList(); ;
        }


        public void AuditProApp(AuditProjectApplicationInPut _app)
        {
            if (!AbpSession.UserId.HasValue)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "请重新登陆系统");
            }
            long userId = AbpSession.UserId.Value;

            var ap = proAppRepository.Get(_app.appId);
            if (ap == null)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "错误的审核记录");
            }

            var hasAuth = permissionService.HasPermission(userId, ap.ProjectId, ProjectFunctions.项目授权);
            if (!hasAuth)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "没有审核权限");
            }
            if (ap.AppStatus != AppStatus.未审核)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "已审核");
            }

            ap.CheckUserId = userId;
            ap.CheckUsers = userManager.Users.Where(x => x.Id == userId).FirstOrDefault().UserName;
            ap.CheckOn = System.DateTime.Now;
            ap.EffectiveTime = _app.effectiveTime;
            ap.ExpirationTime = _app.expirationTime;
            ap.CheckNote = _app.auditRemark;




            #region 项目问题提问
            var projectinfo = proRepository.Get(ap.ProjectId);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectinfo.ProjectName;
            dic["项目编号"] = projectinfo.ProjectNo;
            dic["产品号"] = projectinfo.ProductNo;
            dic["操作时间"] = DateTime.Now.ToString("yyyy-MM-dd");
            dic["操作人"] = ap.CheckUsers;
            dic["申请人"] = userManager.Users.Where(x => x.Id == ap.AppUserId).FirstOrDefault().UserName;
            dic["生效时间"] = _app.effectiveTime.ToString("yyyy-MM-dd");
            dic["失效时间"] = _app.expirationTime.ToString("yyyy-MM-dd");
            dic["审核说明"] = _app.auditRemark;
            #endregion



            if (_app.auditPass)
            {
                ap.AppStatus = AppStatus.已通过;
                var team = new MyCompanyName.AbpZeroTemplate.Prm.Project.ProjectTeam()
                {
                    CreationTime = System.DateTime.Now,
                    StartTime = _app.effectiveTime,
                    EndTime = _app.expirationTime,
                    ProjectId = ap.ProjectId,
                    UserId = ap.AppUserId,
                    ProjectRoleId = projectTmpRoleId
                };
                proTeamRepository.Insert(team); 
                mailManagerRepository.CreateMailRecord(dic, MailCatelog.申请查看项目通过, projectinfo.Id);
            }
            else
            {
                ap.AppStatus = AppStatus.已驳回; 
                mailManagerRepository.CreateMailRecord(dic, MailCatelog.申请查看项目驳回, projectinfo.Id);
            }

        }
    }
}
